package dk.ucn.datamatiker.henrik.bundtkage.earthcake.whereami;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

public class WhereAmIActivity extends Activity {

	private GoogleMap myMap;

	public void onClick(View view) {
		animateMap(globLocation);

		// Intent intent = new Intent(this, MapActivity.class);
		// startActivity(intent);
	}

	// On create
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		LocationManager locationManager;
		String svcName = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(svcName);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setSpeedRequired(false);
		criteria.setCostAllowed(true);
		String provider = locationManager.getBestProvider(criteria, true);

		// String provider = LocationManager.GPS_PROVIDER;
		Location l = locationManager.getLastKnownLocation(provider);

		updateWithNewLocation(l);

		locationManager.requestLocationUpdates(provider, 2000, 10,
				locationListener);

		myMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
				.getMap();

		myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

		try {
			animateMap(globLocation);
		} catch (Exception e) {
			// TODO Auto-generated catch block

		}
	}

	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};

	private Location globLocation;

	private void updateWithNewLocation(Location location) {
		TextView myLocationText;
		myLocationText = (TextView) findViewById(R.id.myLocationText);
		String latLongString = "No location found";

		String addressString = "No address found";

		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			latLongString = "Lat:" + lat + "\nLong:" + lng;

			double latitude = location.getLatitude();
			double longitude = location.getLongitude();

			Geocoder gc = new Geocoder(this, Locale.getDefault());
			try {
				List<Address> addresses = gc.getFromLocation(latitude,
						longitude, 1);
				StringBuilder sb = new StringBuilder();
				if (addresses.size() > 0) {
					Address address = addresses.get(0);
					for (int i = 0; i < address.getMaxAddressLineIndex()-1; i++)
					{
						sb.append(address.getAddressLine(i)).append("\n"); 		// Address + address#
						sb.append(address.getPostalCode()).append(" ");			// Postal code
						sb.append(address.getLocality()).append("\n");			// By
						sb.append(address.getAdminArea()).append("\n");			// Region
						sb.append(address.getCountryName()).append("\n");		// Country
					}
				}
				addressString = sb.toString();
			} catch (IOException e) {
			}
		}
		myLocationText.setText("Your Current Position is:\n" + latLongString
				+ "\n\n" + addressString);
		// myLocationText.setText("Her er du!");

		globLocation = location;
	}

	private void animateMap(Location location) {

		CameraPosition cp = new CameraPosition.Builder()
				.target(new LatLng(location.getLatitude(), location
						.getLongitude())).zoom(12).build();
		myMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
		myMap.setMyLocationEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.where_am_i, menu);
		return true;
	}

}
